<template>
  <div class="trade_main">
    <div class="m_left">
      <div class="m_l_height">
        <div class="ml_1">
          交易区
        </div>
      </div>
      <div class="m_l_main">
        <div class="ml_main_1">
          <Form>
            <FormItem label="合约名称" :label-width="90" style="margin-bottom: 10px; width: 300px" >
              <Select v-model="contractSelected" style="width: 120px" @on-change="contract_selected">
                <Option v-for="(item,contract_key) in contract_list" :value="item" :key="contract_key">{{ item }}</Option>
              </Select>
              <Button @click="update_contract_modall = true;getcontractAll()"style="background: dodgerblue">合约管理</Button>
            </FormItem>
            <FormItem label="市价"  :label-width="90" style="margin-bottom: 10px; width: 330px">
              <p class="price_p">{{liquidation.priceNew}} </p>
            </FormItem>

            <FormItem label="策略种类" :label-width="90" style="margin-bottom: 10px; width: 300px" >
              <Select v-model="tradeValidate.strategy" clearable>
                <Option value="循环策略">循环策略</Option>
                <Option value="关联策略">关联策略</Option>
                <Option value="网络策略">网络策略</Option>
                <Option value="阶梯策略">阶梯策略</Option>
                <Option value="顺势加仓策略">顺势加仓策略</Option>
                <Option value="追踪止盈止损策略">追踪止盈止损策略</Option>
                <Option value="市场浮动策略">市场浮动策略</Option>
              </Select>
            </FormItem>
            <FormItem label="开仓价格"  :label-width="90" style="margin-bottom: 10px; width: 300px">
              <Input class="my-input" type="text" v-model="tradeValidate.open"  placeholder="必选">
                <span slot="append"  style="width: 80px">USD</span>
              </Input>
            </FormItem>
            <FormItem label="平仓价格"  :label-width="90" style="margin-bottom: 10px; width: 300px">
              <Input class="my-input" type="text" v-model="tradeValidate.close"  placeholder="必选">
                <span slot="append"  style="width: 80px">USD</span>
              </Input>
            </FormItem>
            <FormItem label="仓位(张)"  :label-width="90" style="margin-bottom: 10px; width: 300px">
              <Input  class="my-input" type="text" v-model="tradeValidate.volume"  placeholder="必选">
                <span slot="append"  style="width: 80px">张</span>
              </Input>
            </FormItem>
            <FormItem label="基础参数" :label-width="90" style="margin-bottom: 10px; width: 300px" >
              <Select v-model="tradeValidate.basic_id" placeholder="请选择（必填）" >
                <Option :value=base.strategy_id v-for="(base,key1) in base_paramter" :key="key1">{{base.preset_name}}</Option>
              </Select>
            </FormItem>
            <FormItem label="批量配置" :label-width="90" style="margin-bottom: 10px; width: 300px" >
              <Select v-model="tradeValidate.batch_id" placeholder="请选择" clearable >
                <Option :value=batch.strategy_id v-for="(batch,key2) in batch_paramter" :key="key2">{{batch.preset_name}}</Option>
              </Select>
            </FormItem>
            <FormItem label="多单强平" :label-width="90" style="margin-bottom: 10px; width: 300px" >
              <p>{{liquidation.liquidation_buy}}</p>
            </FormItem>
            <FormItem label="空单强平" :label-width="90" style="margin-bottom: 10px; width: 300px" >
              <p  v-if="!(liquidation.liquidation_sell.search('99999999')>=0)">{{liquidation.liquidation_sell}}</p>
              <p style="font-family: not;font-size: 19px" v-else>{{liquidation.liquidation_sell.replace('99999999','+∞')}}</p>
            </FormItem>
            <FormItem label="直涨"  :label-width="90" style="margin-bottom: 10px; width: 330px">
              <div style="display:inline-block;width: 100px">{{liquidation.max_profit_and_loss_data.c1}}</div>
              <div style="display:inline-block;width: 120px"><label style="font-size: 14px;color: #6e7786;height: 42px;">循涨</label>&nbsp &nbsp{{liquidation.max_profit_and_loss_data.c2}}</div>
            </FormItem>
            <FormItem label="直跌"  :label-width="90" style="margin-bottom: 10px; width: 330px">
              <div style="display:inline-block;width: 100px">{{liquidation.max_profit_and_loss_data.c3}}</div>
              <div style="display:inline-block;width: 120px"><label style="font-size: 14px;color: #6e7786;height: 42px;">循跌</label>&nbsp &nbsp{{liquidation.max_profit_and_loss_data.c4}}</div>
            </FormItem>
            <FormItem  style="margin-bottom: 10px; margin-left: 22px">
              <Checkbox label="启动" v-model="tradeValidate.run_or_unrun">启动</Checkbox>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
              <Select v-model="tradeValidate.profit_loss_cal_status_run_and_unrun" style="width: 180px">
                <Option v-for="(item,profit_loss_cal_status_run_and_unrun_key) in profit_loss_cal_status_run_and_unrun_list" :value="item.value" :key="profit_loss_cal_status_run_and_unrun_key">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Form>
          <div class="button_group">
            <Button class="bt1" :disabled ='Number(tradeValidate.open)>=Number(tradeValidate.close) || flag' @click="addStrategy_check">买入/看多</Button>
            <Button class="bt2" :disabled ='Number(tradeValidate.open)<=Number(tradeValidate.close) || flag' @click="addStrategy_check">卖出/看空</Button>
          </div>
        </div>
      </div>
    </div>
    <div class="m_right">
      <div class="m_r_table">
        <Tabs @on-click="tab_parameter">
          <TabPane label="基础参数" name="base">
            <div>
              <Row type="flex" justify="center">
                <Col span="24">
                  <Table  :row-class-name="base_rowClassName"  :columns="basecolumns" :data="base_paramter"  :disabled-hover="true" stripe height="620">
                  </Table>
                </Col>
              </Row>
            </div>
          </TabPane>
          <TabPane label="批量参数" name="batch">
            <div>
              <Row type="flex" justify="center">
                <Col span="24">
                  <Table  :row-class-name="batch_rowClassName"   :columns="batchcolumns" :data="batch_paramter"  :disabled-hover="true" stripe height="620">
                  </Table>
                </Col>
              </Row>
            </div>
          </TabPane>
          <div slot="extra" class="main-row-right-extra">
            <Button type="primary"  @click="add_basic_modall()" v-if="tab_param_daa_button">添加</Button>
            <Button type="primary"  @click="add_batch_modall()" v-if="!tab_param_daa_button">添加</Button>
            <Button @click="close_modal" style="margin-left: 20px">关闭</Button>
          </div>
        </Tabs>
      </div>
    </div>
    <div class="my-Modal">
      <Modal
        v-model="basic_modall"
        :title="basic_modall_title"
        :ok-text = "basic_modall_ok"
        :mask-closable = "false"
        @on-ok ="basic_parameter_save"
        @on-cancel ="basic_parameter_cancel"
        :loading ='true'
        width="440">
        <div>
          <Form>
            <FormItem label="配置名称" :label-width="130" style="margin-bottom: 10px;">
              <Input v-model="add_base_paramter.preset_name" style="width: 230px"></Input>
            </FormItem>
            <FormItem label="循环次数" :label-width="130" style="margin-bottom: 10px;">
              <Input v-model="add_base_paramter.stop_amount_cycle" style="width: 230px">
                <span slot="append"  style="width: 80px">次</span>
              </Input>
            </FormItem>
            <Divider :dashed="true"/>
            <FormItem label="止损价格" :label-width="130" style="margin-bottom: 10px;">
              <Input v-model="add_base_paramter.stop_loss"style="width: 230px" >
                <span slot="append"  style="width: 80px">USD</span>
              </Input>
            </FormItem>
            <FormItem label="止损平仓方式" :label-width="130" style="margin-bottom: 10px;">
              <Select v-model="add_base_paramter.stop_loss_type" style="width: 230px">
                <Option value="被动">被动</Option>
                <Option value="主动">主动</Option>
              </Select>
            </FormItem>
            <FormItem label="止损价格类型" :label-width="130" style="margin-bottom: 10px;">
              <Select v-model="add_base_paramter.stop_loss_price_type" style="width: 230px">
                <Option value="市价">市价</Option>
                <Option value="指数价">指数价</Option>
                <Option value="EMA">EMA</Option>
              </Select>
            </FormItem>
            <Divider :dashed="true"/>
            <FormItem label="止盈价格" :label-width="130" style="margin-bottom: 10px;">
              <Input v-model="add_base_paramter.stop_profit" style="width: 230px">
                <span slot="append"  style="width: 80px">USD</span>
              </Input>
            </FormItem>
            <FormItem label="止盈平仓方式" :label-width="130" style="margin-bottom: 10px;">
              <Select v-model="add_base_paramter.stop_profit_type" style="width: 230px">
                <Option value="被动">被动</Option>
                <Option value="主动">主动</Option>
              </Select>
            </FormItem>
            <FormItem label="止盈价格类型" :label-width="130" style="margin-bottom: 10px;">
              <Select v-model="add_base_paramter.stop_profit_price_type" style="width: 230px">
                <Option value="市价">市价</Option>
                <Option value="指数价">指数价</Option>
                <Option value="EMA">EMA</Option>
              </Select>
            </FormItem>
            <Divider :dashed="true"/>
            <FormItem label="触发时间平仓方式" :label-width="130" style="margin-bottom: 10px;">
              <Select v-model="add_base_paramter.stop_time_type" style="width: 230px">
                <Option value="被动">被动</Option>
                <Option value="主动">主动</Option>
              </Select>
            </FormItem>
            <FormItem label="终止类型" :label-width="130" style="margin-bottom: 10px;">
              <Select v-model="add_base_paramter.stop_time_time_or_len" style="width: 230px">
                <Option value="len">运行时长</Option>
                <Option value="time">终止时间</Option>
                <Option value="None">无限时长</Option>
              </Select>
            </FormItem>
            <FormItem label="运行时长" :label-width="130" style="margin-bottom: 10px;" v-if="add_base_paramter.stop_time_time_or_len === 'len'">
              <Input v-model="add_base_paramter.stop_time_len" style="width: 230px">
                <span slot="append"  style="width: 80px">小时</span>
              </Input>
            </FormItem>
            <FormItem label="终止时间" :label-width="130" style="margin-bottom: 10px;" v-if="add_base_paramter.stop_time_time_or_len === 'time'">
              <DatePicker  type="datetime"  v-model="add_base_paramter.stop_time" style="width: 230px"></DatePicker >
            </FormItem>
            <FormItem label="合约id" :label-width="130" style="margin-bottom: 10px;" v-if="1===3">
              <Input v-model="add_base_paramter.strategy_id" style="width: 230px">
              </Input>
            </FormItem>
          </Form>
        </div>
      </Modal>
      <Modal
        v-model="batch_modall"
        :title="batch_modall_title"
        :ok-text = "batch_modall_ok"
        :mask-closable = "false"
        @on-ok ="batch_parameter_save"
        @on-cancel ="batch_parameter_cancel"
        :loading ='true'
        width="440">
        <div>
          <Form>
            <FormItem label="配置名称" :label-width="120" style="margin-bottom: 10px;">
              <Input v-model="add_batch_paramter.preset_name" style="width: 230px"></Input>
            </FormItem>
            <FormItem label="批量下单方式" :label-width="120" style="margin-bottom: 10px;">
              <Select v-model="add_batch_paramter.batch_kind" style="width: 230px">
                <Option value="等比">浮动比例</Option>
                <Option value="等差">固定数值</Option>
              </Select>
            </FormItem>
            <FormItem label="开仓价格间隔" :label-width="120" style="margin-bottom: 10px;">
              <Input v-model="add_batch_paramter.delt_open" style="width: 230px">
                <span slot="append"  style="width: 80px"  v-if="add_batch_paramter.batch_kind === '等比'">%</span>
                <span slot="append"  style="width: 80px"  v-if="add_batch_paramter.batch_kind === '等差'">点</span>
              </Input>
            </FormItem>
            <FormItem label="平仓价格间隔" :label-width="120" style="margin-bottom: 10px;" >
              <Input v-model="add_batch_paramter.delt_close" style="width: 230px">
                <span slot="append"  style="width: 80px"  v-if="add_batch_paramter.batch_kind === '等比'">%</span>
                <span slot="append"  style="width: 80px"  v-if="add_batch_paramter.batch_kind === '等差'">点</span>
              </Input>
            </FormItem>
            <FormItem label="仓位间隔" :label-width="120" style="margin-bottom: 10px;">
              <Input v-model="add_batch_paramter.delt_volume" style="width: 230px">
                <span slot="append"  style="width: 80px"  v-if="add_batch_paramter.batch_kind === '等比'">%</span>
                <span slot="append"  style="width: 80px"  v-if="add_batch_paramter.batch_kind === '等差'">张</span>
              </Input>
            </FormItem>
            <FormItem label="总单数" :label-width="120" style="margin-bottom: 10px;">
              <Input v-model="add_batch_paramter.amount" style="width: 230px">
              </Input>
            </FormItem>
          </Form>
        </div><!--注册界面组件-->
      </Modal>
      <Modal
        v-model="delete_modall"
        ok-text="确定"
        cancel-text="取消"
        :mask-closable = "false"
        @on-ok="select_remove()"
        :loading ='true'
        @on-cancel="select_remove_cancel()">
        <p>确定要删除吗？</p>
      </Modal>
      <Modal
        v-model="add_strategy_modall"
        ok-text="确定"
        cancel-text="取消"
        :mask-closable = "false"
        :loading ='true'
        @on-ok="addStrategy2()"
      >
        <p>{{add_strategy_modall_title}}</p>
      </Modal>
      <Modal
        v-model="update_contract_modall"
        :title="update_contract_modall_title"
        footer-hide
        :mask-closable = "false"
        :loading ='true'
        width="440">
        <div>
          <Form>
            <Table  :columns="contract_list_all_columns" :data="contract_list_all"  :disabled-hover="true" stripe >
            </Table>
          </Form>
        </div><!--注册界面组件-->
      </Modal>
      <Modal
        v-model="update_contract_confirm_modall"
        ok-text="确定"
        cancel-text="取消"
        :mask-closable = "false"
        @on-ok="select_update()"
        :loading ='true'
        @on-cancel="select_update_cancel()">
        <p>确定要切换吗？</p>
      </Modal>
    </div>
  </div>
</template>

<script>
import {
  TimeToDate,
  isNumberAndNone,
  isPositiveInteger,
  isPositive,
  isNumber,
} from '@/libs/tools'
import {
  inseertParameter,
  deleteParameter,
  updateParameter,
  getLatestLiquidation,
  insertStrategy,
  getParameter,
  getcontract_all,
  getcontract_update,
} from '@/api/trade'
import { mapGetters,mapMutations,mapActions } from 'vuex'
export default {
  name: "trade_main",
  data(){
    return{
      contractSelected: '',
      clientSelected: '',
      contract_list:[],//合约数组
      contract_list_all:[],//合约数组
      contract_list_update_contract:'',//合约数组
      contract_list_all_columns:[
        {
          title: '合约名',
          width: 140,
          align: 'center',
          key: 'contract'
        },
        {
          title: '状态',
          width: 140,
          align: 'center',
          key: 'status'
        },{
          title: '是否切换',
          key: 'action',
          fixed: 'right',
          width: 120,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on:{
                  click: () => {
                    this.click_flag = 1
                    this.update_contract_confirm_modall = true;
                    this.contract_list_update_contract = JSON.parse(JSON.stringify(params.row.contract));
                  }
                }
              }, '切换'),
            ]);
          }
        }],//合约数组
      client_list:[],
      base_paramter: [],//基础参数
      batch_paramter:[],//批量参数
      tradeValidate:{
        strategy:'循环策略',
        open:'',
        close:'',
        volume:'',
        basic_id:'',
        batch_id:'',
        run_or_unrun:false,
        profit_loss_cal_status_run_and_unrun:'none',
      },//交易区
      price:{
        price_now:'',//市价格
        price_index:'',//指数价格
        price_of_stop_profit_and_stop_loss:'',//系统使用的价格
      },
      liquidation:{
        liquidation_buy:'',
        liquidation_sell:'',
        priceNew:'',
        max_profit_and_loss_data: {
          'c1': '',
          'c2': '',
          'c3': '',
          'c4': '',
        }
      },//强平点
      basecolumns:[
        {
          title: '名称',
          align: 'center',
          key: 'preset_name'
        },
        {
          title: '循环次数',
          width: 93,
          align: 'center',
          key: 'stop_amount_cycle'
        },
        {
          title: '止损价格',
          width: 128,
          align: 'center',
          key: 'stop_loss',
          render: (h, params) => {
            if(params.row['stop_loss'] !=='--'){
              return h('span',params.row['stop_loss']+'('+params.row['stop_loss_price_type']+')');
            }else {
              return h('span',params.row['stop_loss']);
            }
          }
        },
        {
          title: '止损方式',
          width: 93,
          align: 'center',
          key: 'stop_loss_type'
        },
        {
          title: '止盈价格',
          width: 128,
          align: 'center',
          key: 'stop_profit',
          render: (h, params) => {
            if(params.row['stop_profit'] !=='--'){
              return h('span',params.row['stop_profit']+'('+params.row['stop_profit_price_type']+')');
            }else {
              return h('span',params.row['stop_profit']);
            }
          }
        },
        {
          title: '止盈方式',
          width: 95,
          align: 'center',
          key: 'stop_profit_type'
        },
        {
          title: '触发时间方式',
          width: 120,
          align: 'center',
          key: 'stop_time_type'
        },
        {
          title: '运行时长',
          width: 95,
          align: 'center',
          key: 'stop_time_len'
        },
        {
          title: '终止时间',
          width: 170,
          align: 'center',
          key: 'stop_time'
        },
        {
          title: '操作',
          key: 'operation',
          align: 'center',
          width: 130,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on:{
                  click: () => {
                    this.basic_modall_title ='修改配置';
                    this.basic_modall_ok = '修改';
                    this.basic_modall = true;
                    this.add_base_paramter = JSON.parse(JSON.stringify(params.row ));
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on:{
                  click: () => {
                    this.delete_modall = true;
                    this.deleteparam  = params;
                    this.deleteparam.type = 'basic';
                    // this.select_remove(params,'basic')
                  }
                }
              }, '删除')
            ]);
          }
        },
      ],
      basedata:[],
      batchcolumns:[
        {
          title: '名称',
          align: 'center',
          key: 'preset_name'
        },
        {
          title: '批量下单方式',
          width: 170,
          align: 'center',
          key: 'batch_kind',
          render:(h,params)=>{
            if(params.row.batch_kind === "等比"){
              return h('span',{

              },"浮动比例")
            }else if(params.row.batch_kind === "等差"){
              return h('span',{

              },"固定数值")
            }
          }
        },
        {
          title: '开仓价格间隔',
          width: 170,
          align: 'center',
          key: 'delt_open'
        },
        {
          title: '平仓价格间隔',
          width: 150,
          align: 'center',
          key: 'delt_close'
        },
        {
          title: '仓位间隔',
          width: 150,
          align: 'center',
          key: 'delt_volume'
        },
        {
          title: '总单数',
          width: 150,
          align: 'center',
          key: 'amount'
        },
        {
          title: '操作',
          key: 'operation',
          align: 'center',
          width: 200,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on:{
                  click: () => {
                    this.batch_modall_title ='修改配置';
                    this.batch_modall_ok = '修改';
                    this.batch_modall = true;
                    this.add_batch_paramter =  JSON.parse(JSON.stringify(params.row));
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on:{
                  click: () => {
                    this.delete_modall = true;
                    this.deleteparam  = params;
                    this.deleteparam.type = 'batch';
                    // this.select_remove(params,'basic')
                  }
                }
              }, '删除')
            ]);
          }
        },
      ],
      batchdata:[],
      add_base_paramter:{
        client_name:'',
        contract:'',
        strategy:'',
        preset_name:'',
        stop_amount_cycle:'',
        stop_loss:'',
        stop_loss_type:'被动',
        stop_loss_price_type:'市价',
        stop_profit:'',
        stop_profit_type:'被动',
        stop_profit_price_type:'市价',
        stop_time_type:'被动',
        stop_time_time_or_len:'None',
        stop_time:'',
        stop_time_len:'',
        basic_or_batch:'',
      },//添加普通参数
      add_batch_paramter:{
        preset_name:'',
        batch_kind:'等差',
        delt_open:'',
        delt_close:'',
        delt_volume:'',
        amount:'',
      },
      basic_modall:false, //基础参数模态框
      batch_modall:false, //批量参数模态框
      delete_modall:false, //删除模态框
      edit_modall:false, //编辑模态框
      basic_modall_title:'', //基础参数模态框的basic_modall_title按钮
      batch_modall_title:'', //批量参数模态框的basic_modall_title按钮
      basic_modall_ok:'',//基础参数模态框的ok按钮
      batch_modall_ok:'',//批量参数模态框的ok按钮
      tab_param_daa_button:true,
      flag : false,//按钮是否可取
      add_strategy_modall : false,//买入卖出二次提示
      add_strategy_modall_title:'',
      loss:'',//止损价
      profit:'',//止赢价
      time:'',
      update_contract_modall:false, //合约可否交易模态框
      update_contract_confirm_modall:false, //合约可否交易模态框
      update_contract_modall_title:'合约交易是否开启',
      click_flag:'',
      profit_loss_cal_status_run_and_unrun_list:[
        {
          'name':'本组',
          'value':'none',
        },
        {
          'name':'已启动+本组',
          'value':'run',
        },
        {
          'name':'已启动+未启动+本组',
          'value':'all',
        },
      ]
    }
  },
  methods:{
    ...mapGetters([
      'get_client',
      'get_contract',
      'get_client_list',
      'get_contract_list',
      'get_base_paramter',
      'get_batch_paramter',
      'get_price',
    ]),
    ...mapMutations([
      'set_contract',
      'set_run_select_Ids',
      'set_unrun_select_Ids',
      'set_run_group',
      'set_unrun_group',
      'set_all_group',
      'set_data_group_id_run',
      'set_data_group_id_unrun',
      'set_client',
      'set_base_paramter',
      'set_batch_paramter',
      'set_contract',
      'set_list_strategy',
      'set_list_strategy_unrun',
      'set_list_strategy_run',
      'set_contract_list',
      'set_client_info',
    ]),
    ...mapActions([
      'getcontract',
      'getBaseParamter',
      'getBatchParamter',
      'getListStrategypro'
    ]),
    addStrategy_check(){
      this.flag = true;//点击之后设置按钮不可使用

      setTimeout(()=>{this.flag = false;}, 1500);
      let _this = this;
      clearTimeout(this.timer);
      let last_open = 1;  //最后一个开仓价
      let last_close = 1; //最后一个平仓价
      //计算最后一个平仓价格
      if(this.tradeValidate.batch_id !=='' && this.tradeValidate.batch_id !==undefined){
        for(let i = 0;i<this.batch_paramter.length;i++){
          if(this.batch_paramter[i].strategy_id ===this.tradeValidate.batch_id){
            console.log("3")
            if(this.batch_paramter[i].batch_kind==='等差'){
              last_open = Number(this.tradeValidate.open) + Number(this.batch_paramter[i].amount-1)*Number(this.batch_paramter[i].delt_open);
              last_close = Number(this.tradeValidate.close) + Number(this.batch_paramter[i].amount-1)*Number(this.batch_paramter[i].delt_close);
              console.log("3-2")
              break;
            }else if(this.batch_paramter[i].batch_kind==='等比'){
              last_open = Number(this.tradeValidate.open)*((1+(Number(this.batch_paramter[i].delt_open)/100)))**Number(this.batch_paramter[i].amount-1);
              last_close = Number(this.tradeValidate.close)*((1+(Number(this.batch_paramter[i].delt_close)/100)))**Number(this.batch_paramter[i].amount-1);
              break;
            }

          }
        }
        if(last_open<=0 || last_close<=0){
          this.$Message.error('批量生产开仓价或者平仓价不能小于0');
          return;
        }
        if(last_close === last_open){
          this.$Message.error('批量生产开仓价不能等于平仓价');
          return;
        }
      }
      if(this.tradeValidate.open !== '' && this.tradeValidate.close !==''
        && this.tradeValidate.volume !== '' && this.tradeValidate.basic_id != ''){
        if(this.tradeValidate.basic_id === undefined){
          this.tradeValidate.basic_id = ''
        }
        if(this.tradeValidate.batch_id === undefined){
          this.tradeValidate.batch_id = ''
        }
        if(!isNumber(this.tradeValidate.open) || !isNumber(this.tradeValidate.close)  || !isNumber(this.tradeValidate.volume)){
          this.$Message.error('必填参数填写有误');
          return;
        }
        else if(this.tradeValidate.open<=0){
          this.$Message.error('开仓价不能小于零');
          return;
        }
        else if(this.tradeValidate.close<=0){
          this.$Message.error('平仓价不能小于零');
          return;
        }
        else if(this.tradeValidate.batch_id !=='' && ((Number(this.tradeValidate.open) - Number(this.tradeValidate.close) >0) !== (Number(last_open) - Number(last_close) >0))){
          this.$Message.error('批量生成有误，请检查');
          return;
        }
        else if(!isPositiveInteger(this.tradeValidate.volume)){
          this.$Message.error('仓位小于零或不是整数');
          return;
        }
      }else {
        this.$Message.error('必填参数没填');
        return;
      }
      this.addStrategy1();
    },
    addStrategy1(){
      let params ={
        client:this.clientSelected,
        contract:this.contractSelected,
        strategy:this.tradeValidate.strategy,
        open:this.tradeValidate.open,
        close:this.tradeValidate.close,
        volume:this.tradeValidate.volume,
        basic_id:this.tradeValidate.basic_id,
        batch_id:this.tradeValidate.batch_id !== '' ?this.tradeValidate.batch_id :'None' ,
        run_or_unrun:this.tradeValidate.run_or_unrun ? 'run' :'unrun' ,
      };
      insertStrategy(params).then(res=>{
        this.add_strategy_modall = false ;
        if(res.data.code === 1000){
          this.$Message.success('成功');
          this.timer =setTimeout(()=>{this.get_ListStrategy2()}, 5000);
        }else {
          this.$Message.error(res.data.data);
        }
      })
        .catch((e) =>{
          this.add_strategy_modall = false ;
          this.$Message.error("失败");
        });


    },
    addStrategy2(){
      let params ={
        client:this.clientSelected,
        contract:this.contractSelected,
        strategy:this.tradeValidate.strategy,
        open:this.tradeValidate.open,
        close:this.tradeValidate.close,
        volume:this.tradeValidate.volume,
        basic_id:this.tradeValidate.basic_id,
        batch_id:this.tradeValidate.batch_id !== '' ?this.tradeValidate.batch_id :'None' ,
        run_or_unrun:this.tradeValidate.run_or_unrun ? 'run' :'unrun' ,
      };
      if(this.click_flag === "addStrategy"){
        this.click_flag = ''
        insertStrategy(params).then(res=>{
          this.add_strategy_modall = false ;
          if(res.data.code === 1000){
            this.$Message.success('成功');
            this.timer =setTimeout(()=>{this.get_ListStrategy2()}, 5000);
          }else {
            this.$Message.error(res.data.data);
          }
        })
          .catch((e) =>{
            this.add_strategy_modall = false ;
            this.$Message.error("失败");
          });
      }
    },
    //获取当前可以交易合约
    get_contract2(){
      let client = this.clientSelected; //用户ID（用户名）
      this.getcontract({client}).then(res =>{
        console.log(res)
      }).catch(err =>{
        console.log(err)
      })
    },
    //获取所有合约
    getcontractAll(){
      let client = this.clientSelected; //用户ID（用户名）
      getcontract_all({client}).then(res =>{
        this.contract_list_all = res.data.data
        console.log(this.contract_list_all);
      }).catch(err =>{
        console.log(err)
      })
    },
    //确认修改
    select_update(){
      let client_name = this.clientSelected;
      let contract = this.contract_list_update_contract;
      if(this.click_flag === 1){
        this.click_flag = ''
        getcontract_update({client_name,contract}).then(res =>{
          if(res.data.code === 1000){
            this.update_contract_modall = false;
            this.update_contract_confirm_modall=false;
            this.$Message.success('切换成功');
            //刷新数据
            this.get_contract2()

          }else {
            this.update_contract_modall = false;
            this.update_contract_confirm_modall=false;
            this.$Message.error(res.data.data);
          }
          // location. reload()
        })
          .catch( err =>{
            this.update_contract_modall = false;
            this.update_contract_confirm_modall=false;
            this.$Message.error('切换失败')
          });
        console.log(this.contract_list_update_contract)
      }


    },
    //取消修改
    select_update_cancel(){
      this.contract_list_update_contract = ''
      this.update_contract_modall = false;
      this.update_contract_confirm_modall=false;
    },
    //获取基础参数
    get_BasicParameter2(){
      let client = this.clientSelected; //用户ID（用户名）
      let contract = this.contractSelected;//合约名称
      this.getBaseParamter({client,contract}).then(res =>{
        console.log(res);
      }).catch(err =>{
        console.log("获取基础参数失败")
      })
    },
    //获取批量参数
    get_BatchParameter2(){
      let client = this.clientSelected; //用户ID（用户名）
      let contract = this.contractSelected;//合约名称
      this.getBatchParamter({client,contract}).then(res =>{
        console.log(res);
      }).catch(err =>{
        console.log(err)
      })
    },
    //当参数页面被选中时
    tab_parameter(name){
      if(name === 'base'){
        this.tab_param_daa_button = true;
        this.get_BasicParameter2();
      }else if(name === 'batch'){
        this.tab_param_daa_button = false;
        this.get_BatchParameter2();
      }
    },
    add_basic_modall(){
      this.add_base_paramter = {
        client_name:'',
        contract:'',
        strategy:'',
        preset_name:'',
        stop_amount_cycle:'',
        stop_loss:'',
        stop_loss_type:'被动',
        stop_loss_price_type:'市价',
        stop_profit:'',
        stop_profit_type:'被动',
        stop_profit_price_type:'市价',
        stop_time_type:'被动',
        stop_time_time_or_len:'None',
        stop_time:'',
        stop_time_len:'',
        basic_or_batch:'',
      };
      this.basic_modall_title ='添加配置';
      this.basic_modall_ok = '添加';
      this.basic_modall = true;
    },
    add_batch_modall(){
      this.add_batch_paramter = {
        preset_name:'',
        batch_kind:'等差',
        delt_open:'',
        delt_close:'',
        delt_volume:'',
        amount:'',
      };
      this.batch_modall_title ='添加配置';
      this.batch_modall_ok = '添加';
      this.batch_modall = true;
    },
    basic_parameter_save(){
      let params = {
        basic_or_batch:'basic',
        preset_name : this.add_base_paramter.preset_name,
        client_name:this.clientSelected,
        contract:this.contractSelected,
        strategy:this.tradeValidate.strategy,
        stop_loss:this.add_base_paramter.stop_loss,
        stop_loss_type:this.add_base_paramter.stop_loss_type,
        stop_loss_price_type:this.add_base_paramter.stop_loss_price_type,
        stop_profit:this.add_base_paramter.stop_profit,
        stop_profit_type:this.add_base_paramter.stop_profit_type,
        stop_profit_price_type:this.add_base_paramter.stop_profit_price_type,
        stop_amount_cycle:this.add_base_paramter.stop_amount_cycle,
        stop_time_type:this.add_base_paramter.stop_time_type,
        stop_time_time_or_len:this.add_base_paramter.stop_time_time_or_len,
      };
      if(this.add_base_paramter.stop_time_time_or_len ==='None'){
        params.stop_time ='None';
        params.stop_time_len ='None'
      }else if(this.add_base_paramter.stop_time_time_or_len == 'time'){
        if(this.add_base_paramter.stop_time === ''){
          this.$Message.error ('运行时间不能未空');
          return;
        }
        params.stop_time =this.add_base_paramter.stop_time.getTime();
        params.stop_time_len ='None'
      }else if(this.add_base_paramter.stop_time_time_or_len == 'len'){
        if(this.add_base_paramter.stop_time_len === '' || this.add_base_paramter.stop_time_len === 'None' ){
          this.$Message.error ('运行时长不能为空');
          return;
        }
        params.stop_time_len =this.add_base_paramter.stop_time_len;
        params.stop_time ='None'
      }
      if(this.basic_modall_ok === '添加'){
        console.log(params);
        inseertParameter(params).then(res=>{
          this.basic_parameter_cancel()
          console.log(res);
          this.basic_modall = false;
          if(res.status === 502){
            this.$Message.error("发生502，请核查基础参数");
            return;
          }
          if(res.data.code === 1000){
            this.$Message.success('添加成功');
            this.get_BasicParameter2()
          }else {
            this.$Message.success('添加失败');
            this.get_BasicParameter2()
          }
          // location. reload()
        }).catch(res=>{
          this.$Message.error("发生502，请核查基础参数");
          return;
        })
      }else if(this.basic_modall_ok === '修改'){
        params.strategy_id=this.add_base_paramter.strategy_id
        updateParameter(params).then(res=>{
          this.basic_parameter_cancel()
          console.log(res);
          this.basic_modall = false;
          if(res.status === 502){
            this.$Message.error("发生502，请核查基础参数");
            return;
          }
          if(res.data.code === 1000){
            this.$Message.success('修改成功');
            this.get_BasicParameter2()
          }else {
            this.$Message.success('修改失败');
          }
          // location. reload()
        }).catch(res=>{
          this.$Message.error("发生502，请核查基础参数");
          return;
        })
      }
    },
    batch_parameter_save(){
      if(this.add_batch_paramter.preset_name == '' || this.add_batch_paramter.batch_kind == ''||
        this.add_batch_paramter.delt_open == '' || this.add_batch_paramter.delt_close == '' ||
        this.add_batch_paramter.delt_volume == '' || this.add_batch_paramter.amount == ''){
        this.$Message.error ('请完善信息');
      }else {
        let params = {
          basic_or_batch:'batch',
          preset_name : this.add_batch_paramter.preset_name,
          client_name:this.clientSelected,
          contract:this.contractSelected,
          strategy:this.tradeValidate.strategy,
          batch_kind:this.add_batch_paramter.batch_kind,
          delt_open:this.add_batch_paramter.delt_open,
          delt_close:this.add_batch_paramter.delt_close,
          delt_volume:this.add_batch_paramter.delt_volume,
          amount:this.add_batch_paramter.amount,
          strategy_id:this.add_batch_paramter.strategy_id,
        };
        if(!isNumber(params.amount) || !isPositiveInteger(params.amount)){
          this.$Message.error('总单数只能是正整数');
          return;
        }
        if(!isNumber(params.delt_volume) || !isPositive(params.delt_volume)){
          this.$Message.error('仓位间隔只能是整数');
          return;
        }
        if(!isNumber(params.delt_open)){
          this.$Message.error('开仓间隔非法字符');
          return;
        }
        if(!isNumber(params.delt_close)){
          this.$Message.error('平仓间隔非法字符');
          return;
        }
        if(params.preset_name.length>64){
          this.$Message.error ('基础配置名称不能超过64个字符');
          return;
        }
        if(this.batch_modall_ok === '添加'){
          inseertParameter(params).then(res=>{
            this.batch_parameter_cancel();
            console.log(res);
            this.batch_modall = false;
            if(res.status === 502){
              this.$Message.error("发生502，请核查批量参数");
              return;
            }
            if(res.data.code === 1000){
              this.$Message.success('添加成功');
              this.get_BatchParameter2()
            }else {
              this.$Message.success('添加失败');
            }
          }).catch(res=>{
            this.$Message.error("发生502，请核查批量参数");
            return;
          })
        }else if(this.batch_modall_ok === '修改'){
          updateParameter(params).then(res=>{
            this.batch_parameter_cancel();
            console.log(res);
            this.batch_modall = false;
            if(res.status === 502){
              this.$Message.error("发生502，请核查批量参数");
              return;
            }
            if(res.data.code === 1000){
              this.$Message.success('添加成功');
              this.get_BatchParameter2()
            }else {
              this.$Message.success('添加失败');
            }
          }).catch(res=>{
            this.$Message.error("发生502，请核查批量参数");
            return;
          })
        }

      }
    },
    close_modal(){
      this.get_BasicParameter2();
      this.get_BatchParameter2();
      this.tradeValidate = {
        strategy:'循环策略',
        open:'',
        close:'',
        volume:'',
        basic_id:'',
        batch_id:'',
        run_or_unrun:false,
        profit_loss_cal_status_run_and_unrun:'none',
      };//交易区
      this.$emit('on-close-modal', {
        close: false,
      })
    },
    //选中删除
    select_remove(){
      let type = this.deleteparam.type;
      let params ={};
      if(type === 'basic'){
        params.basic_or_batch = 'basic'
      }else if(type === 'batch'){
        params.basic_or_batch = 'batch'
      }
      params.strategy_id = this.deleteparam.row.strategy_id;
      deleteParameter(params).then(res =>{
        if(res.status === 502){
          if(type === 'basic'){
            this.$Message.error("发生502，请核查基础参数");
            return;
          }else if(type === 'batch'){
            this.$Message.error("发生502，请核查批量参数");
            return;
          }
        }
        if(res.data.code === 1000){
          this.delete_modall =false;
          this.$Message.success('删除成功');
          if(type === 'basic'){
            this.get_BasicParameter2()
          }else if(type === 'batch'){
            this.get_BatchParameter2()
          }
        }else {
          this.$Message.success('删除失败');
        }
        // location. reload()
      })
        .catch( err =>{
          this.$Message.error('删除失败')
        });
    },
    //选中删除取消
    select_remove_cancel(){
      this.deleteparam = ''
    },
    //关闭页面
    basic_parameter_cancel(){
      this.add_base_paramter = {
        client_name:'',
        contract:'',
        strategy:'',
        preset_name:'',
        stop_amount_cycle:'',
        stop_loss:'',
        stop_loss_type:'被动',
        stop_profit:'',
        stop_profit_type:'被动',
        stop_time_type:'被动',
        stop_time_time_or_len:'None',
        stop_time:'',
        stop_time_len:'',
        basic_or_batch:'',
      }
    },
    //关闭页面
    batch_parameter_cancel(){
      this.add_batch_paramter = {
        client_name:'',
        contract:'',
        strategy:'',
        preset_name:'',
        stop_amount_cycle:'',
        stop_loss:'',
        stop_loss_type:'',
        stop_profit:'',
        stop_profit_type:'',
        stop_time_type:'',
        stop_time_time_or_len:'len',
        stop_time:'',
        stop_time_len:'',
        basic_or_batch:'',
      }
    },
    //获取策略
    get_ListStrategy2(){
      let client = this.clientSelected; //用户ID（用户名）
      let contract = this.contractSelected;//合约名称
      this.getListStrategypro({client,contract}).then(res =>{
        console.log(res);
      }).catch(err =>{
        console.log(err)
      })
    },
    //基础参数颜色
    base_rowClassName (row, index) {
      var patt = /空/;
      if (patt.test(row.preset_name)) {
        return 'demo-table-sell-row';
      } else {
        return 'demo-table-buy-row';
      }
    },
    //批量参数颜色
    batch_rowClassName (row, index) {
      var patt = /空/;
      if (patt.test(row.preset_name)) {
        return 'demo-table-sell-row';
      } else {
        return 'demo-table-buy-row';
      }
    },
    contract_selected(){
      if(this.contractSelected !== undefined){
        this.set_contract(this.contractSelected);
      }
    },
  },
  created(){
    if(this.get_client() != ''){
      this.clientSelected = this.get_client();
    }else {
      this.clientSelected = '';
    }
    if(this.get_contract_list != ''){
      this.contract_list = this.get_contract_list()
    }else {
      this.get_contract2();
    }
    if( this.get_contract() != ''){
      this.contractSelected = this.get_contract();
    }else{
      this.contractSelected = '';
      this.set_contract(this.contractSelected);
    }
    if( this.get_base_paramter() != ''){
      this.base_paramter = this.get_base_paramter();
    }else{
      this.base_paramter = [];
    }
    if( this.get_batch_paramter() != ''){
      this.batch_paramter = this.get_batch_paramter()
    }else{
      this.batch_paramter = [];
    }
  },
  computed:{
    computed_client_list(){
      return this.get_client_list()
    },
    computed_contract_list(){
      return this.get_contract_list()
    },
    computed_client(){   //vux要监听对象
      return this.get_client()
    },
    computed_contract(){
      return this.get_contract()
    },
    computed_price(){
      return this.get_price()
    },
    computed_base_paramter(){
      return this.get_base_paramter()
    },
    computed_batch_paramter(){
      return this.get_batch_paramter()
    },
    client_and_contract(){   //如果client和contract都发生改变执行
      const  { clientSelected,contractSelected} = this;
      return {
        clientSelected,
        contractSelected
      }
    },
  },
  watch:{
    computed_client_list(){
      this.client_list = this.get_client_list();
    },
    computed_contract_list(){
      this.contract_list = this.get_contract_list()
    },
    computed_client(){
      this.clientSelected = this.get_client();
    },
    computed_contract(){
      this.contractSelected = this.get_contract()
    },
    computed_price(){
      this.price = this.get_price();
    },
    computed_base_paramter(){
      this.base_paramter = this.get_base_paramter();
      if(this.base_paramter!=undefined){
        this.base_paramter = this.base_paramter.map(    //时间戳转时间
          function(current, index, array){
            if(current.stop_time !== 'None'){
              current.stop_time = TimeToDate(current.stop_time, 'year')
            }
            if(current.stop_time_len =='None'){
              current.stop_time_len = ''
            }
            if(current.stop_time =='None'){
              current.stop_time = ''
            }
            return current
          }
        );
      }
    },
    computed_batch_paramter(){
      this.batch_paramter = this.get_batch_paramter();
    },
    client_and_contract(){ //获取到用户id和合约后执行的方法
      if(this.clientSelected !== '' && this.contractSelected !=='' && this.contractSelected !==undefined){
        this.get_BasicParameter2();
        this.get_BatchParameter2();
      }
    },
    tradeValidate:{
      handler(newName, oldName) {
        if(this.tradeValidate.open !== '' && this.tradeValidate.close !=='' && this.tradeValidate.volume !== '' && this.tradeValidate.basic_id !== ''
        ){
          if(this.tradeValidate.batch_id === undefined){
            this.tradeValidate.batch_id = ''
          }
          let params ={
            client:this.clientSelected,
            contract:this.contractSelected,
            strategy:this.tradeValidate.strategy,
            open:this.tradeValidate.open,
            close:this.tradeValidate.close,
            volume:this.tradeValidate.volume,
            basic_id:this.tradeValidate.basic_id,
            batch_id:this.tradeValidate.batch_id !== '' ?this.tradeValidate.batch_id :'None' ,
            profit_loss_cal_status_run_and_unrun:this.tradeValidate.profit_loss_cal_status_run_and_unrun,
          };
          getLatestLiquidation(params).then(res=>{
            if (res.data.code === 1000){
              this.liquidation = res.data.data
            }else {
              this.liquidation = {
                liquidation_buy:'强平点计算失败，请检查参数',
                liquidation_sell:'强平点计算失败，请检查参数',
                priceNew:'',
                max_profit_and_loss_data: {
                  'c1': '',
                  'c2': '',
                  'c3': '',
                  'c4': '',
                }
              }
            }

          });
        }else{
          this.liquidation = {
            liquidation_buy:'',
            liquidation_sell:'',
            priceNew:'',
            max_profit_and_loss_data: {
              'c1': '',
              'c2': '',
              'c3': '',
              'c4': '',
            }
          }
        }
      },
      deep: true
    },
    contractSelected(){
      this.set_client_info(
        {
          basic:{
            static:'',
            buy_volume:'',
            sell_volume:'',
            profit_real:'',
            profit_unreal:'',
            cny:'',
            lowest_net_worth:'',
          }, //基本信息
          risk:{
            end_down:'',
            end_down_type:'',
            end_down_price_type:'',
            end_up:'',
            end_up_type:'',
            end_up_price_type:'',
            end_time:'',
          },  //风险控制
        }
      );
      this.set_run_select_Ids([]);
      this.set_unrun_select_Ids([]);
      this.set_run_group([]);
      this.set_unrun_group([]);
      this.set_all_group([]);
      this.set_data_group_id_run([]);
      this.set_data_group_id_unrun([]);
      this.set_base_paramter([]);
      this.set_batch_paramter([]);
      this.set_list_strategy([]);
      this.set_list_strategy_unrun([]);
      this.set_list_strategy_run([]);
    }
  }
}
</script>

<style scoped lang="less">
button {
  border: 0;
  border-radius: 4px;
  font-size: 14px;
  letter-spacing: 0;
  cursor: pointer;
}
.trade_main{
  height: 740px;
  display: flex;
  color: #EFEFEF;
  .m_left{
    width: 380px;
    .m_l_height{
      height: 60px;
      .ml_1{
        font-size: 14px;
        padding-top: 19px;
        padding-left: 24px;
      }
    }
    .m_l_main{
      margin-left: 36px;
      margin-top: 18px;
      .ml_main_1{
        margin-top: 10px;
        .price_p{
          font-weight: bold;
        }
        .button_group{
          margin-top: 20px;
          button{
            width: 100px;
            height: 36px;
            color: #FFFFFF;
            border-radius: 2px;
          }
          .bt1{
            background: #39B454;
          }
          .bt2{
            margin-left: 40px;
            background: #E54A4A;;
          }
        }
      }
    }
  }
  .m_right{
    width: 1205px;
    padding-left: 10px;
    .ivu-tabs ,/deep/ .ivu-tabs-nav .ivu-tabs-tab-active{
      color: #EFEFEF;
    }
    /deep/ .ivu-tabs-ink-bar{
      background-color: #EFEFEF;
    }
    .m_r_table{
      height: 60px;
      user-select: none;
      /deep/.ivu-tabs-bar,/deep/ .ivu-tabs-nav{
        margin-bottom: 0;
        border-bottom: 0;
        line-height: 40px;
        height: 60px;
      }
      /deep/ .ivu-table th{
        border: 0;
      }
      /deep/ .ivu-table td{
        border: 0;
        background-color: transparent;
      }
      /deep/ .ivu-table:before{
        height: 0;
      }
      .main-row-right-extra{
        margin-top: 5px;
        margin-right: 27px;
      }
    }
    /deep/ .ivu-table{
      background-color: transparent;
    }
  }
}
</style>
